//
//  AppDelegate.m
//  EcmDoctor
//
//  Created by 张进 on 15/5/29.
//  Copyright (c) 2015年 张进. All rights reserved.
//

#import "AppDelegate.h"
#import "CustomURLCache.h"
#import "JPUSHService.h"
#import "UMCheckUpdate.h"
#import "MobClick.h"
#import "RefreshToken.h"
#import "badgeUrl.h"

@interface AppDelegate () {
    int pageId;
}

@property (nonatomic, copy) NSString *doctor_id;
@property (nonatomic, copy) NSString *moduleName;
@property (nonatomic, copy) NSString *methodname;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    CustomURLCache *cache = [[CustomURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                    diskCapacity:20 * 1024 * 1024
                                    diskPath:nil];
    
    [NSURLCache setSharedURLCache:cache];
    //
   // [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:APP_KEY];
    
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    // Required
    //如需兼容旧版本的方式，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化和同时使用pushConfig.plist文件声明appKey等配置内容。
    
    [JPUSHService setupWithOption:launchOptions appKey:@"3c1c962fdc03ac493d3d05bf" channel:@"doctor" apsForProduction:NO];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(jPushNetworkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    //56d6864a67e58e9e50000f06
    
    [MobClick startWithAppkey:@"56d6864a67e58e9e50000f06" reportPolicy:BATCH  channelId:@"site"];
    //官网
    [UMCheckUpdate checkUpdate:@"有新版本" cancelButtonTitle:@"不更新" otherButtonTitles:@"更新" appkey:@"56d6864a67e58e9e50000f06" channel:@"site"];
    //version标识
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];

    
    
    [NSTimer scheduledTimerWithTimeInterval:1200 target:self selector:@selector(refreshToken) userInfo:nil repeats:YES];
    
    //创建badgeLab
    _onLineBadge =[[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/3-28, 5, 18, 18)];
    _onLineBadge.backgroundColor=[UIColor colorWithRed:238 green:0 blue:0 alpha:1];
    _onLineBadge.textAlignment=NSTextAlignmentCenter;
    _onLineBadge.clipsToBounds=YES;
    _onLineBadge.layer.cornerRadius=9;
    _onLineBadge.textColor=[UIColor whiteColor];
    _onLineBadge.font=[UIFont systemFontOfSize:13];
    
    _telBadge =[[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/3*2-28, 5, 18, 18)];
    _telBadge.backgroundColor=[UIColor colorWithRed:238 green:0 blue:0 alpha:1];
    _telBadge.textAlignment=NSTextAlignmentCenter;
    _telBadge.clipsToBounds=YES;
    _telBadge.layer.cornerRadius=9;
    _telBadge.textColor=[UIColor whiteColor];
    _telBadge.font=[UIFont systemFontOfSize:13];
    
    _clinicBadge =[[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth-28, 5, 18, 18)];
    _clinicBadge.backgroundColor=[UIColor colorWithRed:238 green:0 blue:0 alpha:1];
    _clinicBadge.textAlignment=NSTextAlignmentCenter;
    _clinicBadge.clipsToBounds=YES;
    _clinicBadge.layer.cornerRadius=9;
    _clinicBadge.textColor=[UIColor whiteColor];
    _clinicBadge.font=[UIFont systemFontOfSize:13];
    
    _diagnoseBadge =[[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/3-38, kScreenHeight-114, 18, 18)];
    _diagnoseBadge.backgroundColor=[UIColor colorWithRed:238 green:0 blue:0 alpha:1];
    _diagnoseBadge.textAlignment=NSTextAlignmentCenter;
    _diagnoseBadge.clipsToBounds=YES;
    _diagnoseBadge.layer.cornerRadius=9;
    _diagnoseBadge.textColor=[UIColor whiteColor];
    _diagnoseBadge.font=[UIFont systemFontOfSize:13];
    
    
    return YES;
}

-(void)refreshToken
{
    [[NSUserDefaults standardUserDefaults]setObject:@"refreshtoken" forKey:@"refreshtoken"];
    [RefreshToken changeTokenfailure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}
- (void)jPushNetworkDidReceiveMessage:(NSNotification *)notification {
    
    //  1
    NSDictionary * userInfo = [notification userInfo];
    //  2
    NSString *content = [userInfo valueForKey:@"content"];
    //提示  医生 接单了  或者  结束了
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示：" message:content delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alertView.tag = 521;
    [alertView show];
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [JPUSHService handleRemoteNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark 更新badge值
- (void)upDateBadgemethod:(NSString *)method andLab:(UILabel *)lab {
    
    NSString *docId = [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
    [badgeUrl badgeWithdoctor_info_id:docId moduleName:@"DoctorRS" methodname:method success:^(NSString *badgeNumber) {
        
        lab.text = badgeNumber;
        if ([badgeNumber isEqualToString:@"0"]) {
            lab.alpha = 0;
        }
        
    } failure:^(NSError *error) {
        
    }];
}

@end
